import numpy as np
import matplotlib.pyplot as plt
from rk45 import cal_temperature
import time
from data_record import data_record
R_1 = 0.0012
R_2 = 0.0093
C_in = 1100000
C_wall = 186000000
theta_out = -20
dt = 10

cal_temp = []
dr = []
# init
for i in range(600):
    cal_temp.append(cal_temperature(dt, R_1, R_2, C_in, C_wall))
    dr.append(data_record(i,'test'))
    if(i%2 == 0):
        cal_temp[i].reset_B_P()
    else:
        cal_temp[i].reset_B_0()

    cal_temp[i].reset_out_tempurature(theta_out)
    # cal_temp[i].set_start_theta(np.random.uniform(18, 22), 16.5)

# cal

limit_device_num = int(300)
max_limit_device_num  = int(600)
min_limit_device_num  = int(1)

out_flag = False
loop_times = 0

while True:
    last_time = time.time()
    while loop_times < 4 and out_flag == False:
        print("loop_times {}".format(loop_times))
        loop_times += 1
        for i in range(600):
            cal_temp[i].set_start_theta(np.random.uniform(18, 22),14.808)
            all_temp = np.zeros((600))
        for index in range(int((3600*4)/dt)):
            if(out_flag is True):
                break
            if(index%(6) == 0):
                for i in range(600):
                    all_temp[i] = cal_temp[i].get_theta()[0,0]
                    dr[i].data_append(index,cal_temp[i].get_theta()[0,0],cal_temp[i].get_theta()[1,0],cal_temp[i].P_status)
                    cal_temp[i].reset_B_0()
                    if(all_temp[i] > 22):
                        out_flag = True
                result = np.argpartition(all_temp, limit_device_num)
                for k in result[:limit_device_num]:
                    # if(all_temp[k] < 22):
                    cal_temp[k].reset_B_P()
            for i in range(600):
                cal_temp[i].rk45()


    if(out_flag is True):
        max_limit_device_num = limit_device_num
        limit_device_num = int((limit_device_num+ min_limit_device_num)/2)
        
    else:
        min_limit_device_num = limit_device_num
        limit_device_num = int((limit_device_num+ max_limit_device_num)/2)
            # dr[i].data_append(index,cal_temp[i].get_theta()[0,0],cal_temp[i].get_theta()[1,0],cal_temp[i].P_status)
    print("status: {}new limit_device_num {},cost time {}s".format(out_flag,limit_device_num,time.time() - last_time))
    out_flag = False
    loop_times = 0

# read data and plot
for i in range(6):
    dr[i].data_dump()

    plot_data = dr[i].data_get()
    x_axis = plot_data[:,0]/360
    temp_in = plot_data[:,1]
    temp_wall = plot_data[:,2]
    P_status = plot_data[:,3]
    plt.plot(x_axis,temp_in)
    plt.plot(x_axis,temp_wall)
plt.show()

